#!/usr/bin/perl
# 2014/02/07 extract values from specific area to draw graph

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if(@ARGV != 4 or $ARGV[0] eq '--help'){
	die "Usage : $0 -w [wig file] -r [locaion ex. I:2000-3000]\n";
}

my %opt;
getopts("w:r:", \%opt);

my $FILE_wig = $opt{w};
my $target_location = $opt{r};
my ($target_chr, $target_regions) = split /:/, $target_location;
my ($target_start, $target_end) = split /-/, $target_regions;


#---------------------------------------
# read wig file
#---------------------------------------
#track type=wiggle_0 name=pKu70
#variableStep chrom=chr1 span=30
#50      33.541859
#80      29.758246
#110     26.788264
#140     24.255730
#170     21.654645
#200     19.378484
{
	my $fh;
	if($FILE_wig =~ /\.gz/){
		$fh = IO::File->new("gzip -dc $FILE_wig |") or die "cannot open $FILE_wig: $!";
	}else{
		$fh = IO::File->new($FILE_wig) or die "cannot open $FILE_wig: $!";
	}
	$fh->getline();
	my $chr = '';
	while($_ = $fh->getline()){
		s/\r?\n//;
		if(m/chrom=(\w+) /){
			$chr = $1;
		}else{
			my ($pos, $value) = split /\t/;
			if($value < 0){
				$value = 0;
			}
			if($chr eq $target_chr){
				if($target_start <= $pos and $pos <= $target_end){
					print "$pos\t$value\n";
				}
			}
		}
	}
	$fh->close();
}







